import { useState } from 'react';
import { Form, Button } from 'antd';

const FormItem = Form.Item;
export function AxForm(props) {
  const [confirmLoading, setConfirmLoading] = useState(false);
  const { children, handleVisible, form, handleCreate, ...rest } = props;

  /** 保存 */
  const handleSubmit = e => {
    e.preventDefault();
    if (handleCreate) {
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        setConfirmLoading(true);

        /** 处理提交的时间格式 */
        for (let p in fieldsValue) {
          if (p.toLowerCase().indexOf('time') > -1) {
            const v = fieldsValue[p];
            if (v && v.length === 2 && v[0].format && v[1].format) {
              fieldsValue[p] = v[0].format(v._f) + '~' + v[1].format(v._f);
              fieldsValue[p + 'Start'] = v[0].format(v._f);
              fieldsValue[p + 'End'] = v[1].format(v._f);
            } else if (v && v.format && v._f) {
              fieldsValue[p] = v.format(v._f);
            }
          }
        }

        handleCreate(fieldsValue)
          .catch(() => {
            setConfirmLoading(false);
          })
          .finally(() => {
            setConfirmLoading(false);
          });
      });
    }
  };
  return (
    <Form
      onSubmit={handleSubmit}
      // hideRequiredMark    //隐藏必填标记
      style={{
        marginTop: 8,
      }}
      {...rest}
    >
      {children}
      <FormItem
        // {...submitFormLayout}
        style={{
          marginTop: 32,
          float: 'right',
        }}
      >
        <Button onClick={() => (handleVisible ? handleVisible() : null)}>取消</Button>
        <Button type="primary" htmlType="submit" loading={confirmLoading} style={{ marginLeft: 8 }}>
          保存
        </Button>
      </FormItem>
    </Form>
  );
}
